<?php
class BDA_Tracker {
    public static function init() {
        if (!is_admin()) {
            add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_scripts']);
            add_action('wp_login', [__CLASS__, 'track_user_login'], 10, 2);
            add_action('wp_logout', [__CLASS__, 'track_user_logout']);
            add_action('woocommerce_new_order', [__CLASS__, 'track_new_order']);
        }
    }

    public static function enqueue_scripts() {
        wp_enqueue_script(
            'bda-tracker',
            BDA_PLUGIN_URL . 'assets/js/tracker.js',
            ['jquery'],
            BDA_VERSION,
            true
        );
        
        wp_localize_script('bda-tracker', 'bdaTracker', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('bda-tracker-nonce'),
            'user_id' => get_current_user_id()
        ]);
    }
    
    public static function track_user_login($user_login, $user) {
        global $wpdb;
        
        $wpdb->insert(
            $wpdb->prefix . 'analytics_user_actions',
            [
                'user_id' => $user->ID,
                'session_id' => self::get_session_id(),
                'action_type' => 'login',
                'ip_address' => $_SERVER['REMOTE_ADDR'],
                'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                'created_at' => current_time('mysql')
            ]
        );
    }
    
    private static function get_session_id() {
        if (empty($_COOKIE['bda_session_id'])) {
            $session_id = md5(uniqid(wp_rand(), true));
            setcookie('bda_session_id', $session_id, time() + 3600 * 24, '/');
            return $session_id;
        }
        return $_COOKIE['bda_session_id'];
    }
    
    public static function detect_bots() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $is_bot = preg_match('/bot|crawl|slurp|spider|mediapartners/i', $user_agent);
        
        if ($is_bot) {
            self::log_bot_attempt();
            wp_die('Access denied', 403);
        }
    }
    
    private static function log_bot_attempt($ip = null) {
        global $wpdb;
        $wpdb->insert(
            $wpdb->prefix . 'analytics_user_actions',
            [
                'action_type' => 'bot_attempt',
                'ip_address' => $ip ?? $_SERVER['REMOTE_ADDR'],
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'created_at' => current_time('mysql')
            ]
        );
    }
    
    public static function track_new_order($order_id) {
        global $wpdb;
        
        $order = wc_get_order($order_id);
        if (!$order) return;
    
        // 记录订单基本信息
        $wpdb->insert(
            $wpdb->prefix . 'analytics_user_actions',
            [
                'user_id' => $order->get_customer_id(),
                'session_id' => self::get_session_id(),
                'action_type' => 'new_order',
                'ip_address' => $order->get_customer_ip_address(),
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'created_at' => current_time('mysql')
            ]
        );
    
        // 记录订单商品数据
        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            $wpdb->insert(
                $wpdb->prefix . 'analytics_purchases',
                [
                    'order_id' => $order_id,
                    'user_id' => $order->get_customer_id(),
                    'product_id' => $product->get_id(),
                    'category_id' => $product->get_category_ids()[0] ?? 0,
                    'quantity' => $item->get_quantity(),
                    'total_price' => $item->get_total(),
                    'purchase_date' => $order->get_date_created()->format('Y-m-d H:i:s')
                ]
            );
        }
    }
}